package org.tinygroup.bizframe.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.tinygroup.beancontainer.BeanContainerFactory;
import org.tinygroup.bizframe.common.AuditLogger;
import org.tinygroup.bizframe.common.BaseController;
import org.tinygroup.bizframe.service.inter.SysMenuService;
import org.tinygroup.bizframe.service.inter.dto.complex.UserInfo;
import org.tinygroup.cache.Cache;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;
import org.tinygroup.menuframe.config.Menu;
import org.tinygroup.menuframe.dto.MenuInfo;
import org.tinygroup.menuframe.dto.MenuNode;
import org.tinygroup.menuframe.manager.MenuTreeManager;

public class AuthInterceptor implements HandlerInterceptor {
    private static final String USER_AUTH_MENUS = "authMenus";
    private static final String USER_MENU_PATHS = "menuPaths";

    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    private Cache cache;

    public Cache getCache() {
        return cache;
    }

    public void setCache(Cache cache) {
        this.cache = cache;
    }
    private static AuditLogger auditLogger;
    protected AuditLogger getAuditLogger(){
        if(auditLogger==null){
        	auditLogger = BeanContainerFactory.getBeanContainer(BaseController.class.getClassLoader()).getBean("auditLogger");
        }
        return auditLogger;
    }

    /**
     * 登录控制
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestUrl = httpServletRequest.getRequestURI()
                .replace(httpServletRequest.getContextPath(), "");
        UserInfo userInfo = (UserInfo) httpServletRequest.getSession().getAttribute("userInfo");
        SysMenuService sysMenuService = null;
        List<Integer> userMenuIdList = null;
        sysMenuService = BeanContainerFactory.getBeanContainer(this.getClass().getClassLoader())
        		.getBean("sysMenuServiceImpl");
        
        if(sysMenuService != null){
        	userMenuIdList = sysMenuService.findMenuIdsByUser(userInfo.getUserId());
        	if(userMenuIdList!=null && userMenuIdList.size()>0){
        		getCache().put("authMenus","listUserMenuId-"+userInfo.getUserId(), userMenuIdList);
        	}
        }
        else{
        	userMenuIdList=(List<Integer>)(getCache().get("authMenus", "listUserMenuId-"+userInfo.getUserId()));
        }
        
        /*
        List<SysMenuDto> allMenuList = sysMenuService.getSysMenuList(null);
        List<Menu> menuList = new ArrayList<Menu>();
        for(SysMenuDto sysMenuDto:allMenuList){
            Menu menu = BeanUtil.copyProperties(Menu.class,sysMenuDto);
            menu.setId(sysMenuDto.getMenuId());
            menu.setUrl(sysMenuDto.getMenuUrl());
            menu.setMenuIcon(sysMenuDto.getMenuIcon());
            logger.warnMessage("menu:{0}-->{1}", menu.getMenuName(),menu.getMenuIcon());
            menuList.add(menu);
        }
        //menuNodeList可以做缓存
        
        menuTreeManager.load(menuList);
        */
        
        MenuTreeManager menuTreeManager=BeanContainerFactory.getBeanContainer(this.getClass().getClassLoader())
        		.getBean("menuTreeManager");
        List<MenuNode> menuNodeList = menuTreeManager.getAuthMenuNodeList(userMenuIdList);
        
        //分成两步是为了方便缓存
        MenuInfo menuInfo = menuTreeManager.getAuthMenuInfo(requestUrl,menuNodeList);
        httpServletRequest.setAttribute(USER_MENU_PATHS,menuInfo.getMenuPaths());
        httpServletRequest.setAttribute(USER_AUTH_MENUS,menuInfo.getMenuList());
        
        if((httpServletRequest.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( httpServletRequest.getHeader("X-Requested-With").toString()))){
        	logger.logMessage(LogLevel.INFO, "[Ajax request] userId:{0},url:{1}",userInfo.getUserId(),requestUrl);
        }
        else if(menuInfo.getMenuPaths().size()>0){
        	Integer menuId= menuInfo.getMenuPaths().get(menuInfo.getMenuPaths().size()-1);
        	String menuName = null;
        	List<Menu> allMenu = menuTreeManager.getAllMenu(null);
        	for(Menu m : allMenu){
        		if(m.getId()==menuId.intValue()){
        			menuName =m.getMenuName();
        			break;
        		}
        	}
        	getAuditLogger().logData(userInfo.getUserId(),new String[]{"auditType","功能访问","URL",requestUrl,"菜单Id",menuId+"","菜单名称",menuName});
        	
        }
        return true;
    }


    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 异常处理
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
